package com.example.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.pojo.RespInfo;
import com.example.utils.weixin.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * @author Zhaoluowei
 * @version 1.0
 * @date 2019/7/26 10:38
 */
@RestController
@RequestMapping(value = "/wx")
@Slf4j
public class WxWebController {


    @RequestMapping(value = "/goPay")
    public RespInfo goPay(@RequestBody JSONObject jObject) throws Exception {
        log.info("得到商品信息 -- " + jObject);
        RespInfo respInfo = new RespInfo();
        //o_y3I5SUcG67yBC-ZvLcW1rTbSDc
        String openid = jObject.getString("openId");


        //先请求沙箱的key
        SortedMap<String, Object> sortedMap2 = ClientUtils.getMap2();
        //对订单参数进行排序 并进行& 拼接
        String paramStr = ClientUtils.formatUrlMap(sortedMap2, false, false);
        log.info("订单参数数据用&拼接 --   \n" + paramStr);
        //MD5 获取sign
        String sign = MD5.MD5Encode(paramStr + "&key=" + Configure.key, "UTF-8").toUpperCase();
        log.info("\n" + " 第一次签名 sign   " + sign); //32位的
        //调用加签的方法
        String sandBoxParam = ClientUtils.sendSandBoxParam(sortedMap2, sign);
        log.info("请求参数 --> \n" + sandBoxParam);
        String remotePortData = ClientUtils.getRemotePortData("https://api.mch.weixin.qq.com/sandboxnew/pay/getsignkey", sandBoxParam);
        log.info("验签秘钥返回 -- \n" + remotePortData);

        //解析沙箱环境的sandbox_signkey
        Map<String, String> doXMLParse = ClientUtils.doXMLParse(remotePortData);
        String sandboxSignkey = doXMLParse.get("sandbox_signkey");
        log.info("沙箱环境下签名key --> 0" + sandboxSignkey);

        //获取订单信息
        String orderNo = ClientUtils.getOrderNo();
        log.info("生成订单号 --> \n" + orderNo);

        //拼接订单数据
        SortedMap<String, Object> sortedMap = ClientUtils.getMap("sandbox-test", orderNo, "350000", openid, "127.0.0.1", "http://127.0.0.1:8080");
        log.info("拼接订单数据 --> \n" + sortedMap);

        //对订单参数进行排序 并进行& 拼接
        String paramStr2 = ClientUtils.formatUrlMap(sortedMap, false, false);
        //MD5 获取sign
        String sign2 = MD5.MD5Encode(paramStr2 + "&key=" + sandboxSignkey, "UTF-8").toUpperCase();
        String url = "https://api.mch.weixin.qq.com/sandboxnew/pay/unifiedorder";
        String remotePortData2 = ClientUtils.getRemotePortData(url, ClientUtils.sendParam(sortedMap, sign2));
        log.info("\n" + " 调用下单接口响应   " + remotePortData2);

        //解析调起支付返回的参数
        Map<String, String> doXMLParse2 = ClientUtils.doXMLParse(remotePortData2);
        log.info("调起微信支付的参数 --> \n" + doXMLParse2);

//        // 把 下单参数 和 签名作为参数调用下单接口
//        String url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
//        log.info("\n" + " 调用下单接口传入参数   " +  ClientUtils.sendParam(sortedMap, sign));
        //获取调起 微信支付沙箱参数
        if (doXMLParse2 != null) {
            if ("SUCCESS".equals(doXMLParse2.get("return_code")) && "SUCCESS".equals(doXMLParse2.get("result_code"))) {
                String prepayId = doXMLParse2.get("prepay_id");
                String appid = doXMLParse2.get("appid");
                log.info(" prepayId --> " + prepayId);

                //微信二次加密
                /**
                 * 微信二次加密所需要参数(参数都是key value 形式)
                 * 小程序ID、时间戳、随机串、
                 * 数据包 (package  prepay_id=wx2017033010242291fcfe0db70013231072)
                 * 签名方式 (signType MD5) 默认是MD5
                 */

                //加密所需参数
                SortedMap<String, Object> paraMap = new TreeMap<String, Object>();
                String timeStamp = String.valueOf(System.currentTimeMillis());
                String nonceStr = RandomStringGenerator.getRandomStringByLength(32);

                paraMap.put("appId",appid);
                paraMap.put("timeStamp",timeStamp);
                paraMap.put("nonceStr",nonceStr);
                paraMap.put("package","prepay_id="+prepayId);
                paraMap.put("signType","MD5");

                /**
                 * 加密算法
                 * paySign =
                 * MD5(appId=wxd678efh567hg6787&nonceStr=5K8264ILTKCH16CQ2502SI8ZNMTM67VS&package=prepay_id=wx2017033010242291fcfe0db70013231072&signType=MD5&timeStamp=1490840662&key=qazwsxedcrfvtgbyhnujmikolp111111)
                 * = 22D9B4E54AB1950F51E0649E8810ACD6
                 *
                 */
                String stringA = ClientUtils.formatUrlMap(paraMap, false, false);
                log.info("二次签名 前： " + stringA);

                String signSecond = MD5.MD5Encode(stringA + "&key=" + sandboxSignkey, "UTF-8").toUpperCase();
                log.info("二次签名： " + signSecond);

                JSONObject resultJson = new JSONObject();
                resultJson.put("appId", appid);
                resultJson.put("sign", signSecond);
                resultJson.put("nonceStr", nonceStr);
                resultJson.put("timeStamp", timeStamp);
                resultJson.put("package", "prepay_id=" + prepayId);

                log.info("传给前台参数 " + resultJson);

                // 返回支付信息
               return respInfo.setCode(0).setMessage("success").setData(resultJson);

            }
        }

        log.info("返回前端信息 -- ");
        return respInfo.setCode(1).setMessage("error").setData("");
    }


    //微信支付订单查询
    // https://api.mch.weixin.qq.com/sandboxnew/pay/orderquery
    @RequestMapping(value = "/querySandBoxPayOrder")
    public RespInfo queryWeiXinPayByOrderNo(String orderNo){
        RespInfo respInfo = new RespInfo();






        return  respInfo;
    }




}
